import Vue from 'vue'
import VueRouter from 'vue-router'
// import Login from '@/views/Login/index.vue'
import layout from '@/views/Layout/index.vue'
import Home from '@/views/Home/index.vue'
import User from '@/views/User/index.vue'
import Search from '@/views/Search/index.vue'
import SearchResult from '@/views/Search/SearchResult.vue'
import ArticleDetail from '@/views/ArticleDetail'
import UserEdit from '@/views/User/UserEdit.vue'
import Chat from '@/views/Chat/index.vue'
import { getToken } from '@/utils/token.js'
Vue.use(VueRouter)

// 路由懒加载可以让第一个页面加载的app.js容量小一点，打开网页速度快一些
const routes = [
  { path: '/', redirect: '/login' },
  { path: '/login', component: () => import(/* webpackChunkName: "Login" */ '@/views/Login/index.vue') }, // 路由懒加载
  // 登录后的页面
  {
    path: '/layout',
    component: layout,
    children: [
      { path: 'home', component: Home, meta: { scrollT: 0 } }, // 首页一开始滚动条的位置
      { path: 'user', component: User }
    ]
  },
  { path: '/search', component: Search },
  // 搜索结果页面 , props: true
  { path: '/searchResult/:kw', component: SearchResult },

  // 文字详情页面
  { path: '/article_detail', component: ArticleDetail },

  // 用户信息编辑界面
  { path: '/user_editor', component: UserEdit },

  // 小思同学
  { path: '/chat', component: Chat }
]

const router = new VueRouter({
  routes
})

// 路由全局前置守卫
router.beforeEach((to, from, next) => {
  if (getToken()?.length > 0 && to.path === '/login') {
    // next(false) // 留在原地
    next('/layout/home') // 强制回到首页
  } else {
    next() // 其他情况放行
  }
})
export default router
